<template>
  <div class="app-container">
    <el-tabs tab-position="left">
      <!-- 基本设置 Tab Pane -->
      <el-tab-pane label="账号信息">
        <div class="w-full">
          <el-card>
            <!-- 头像和昵称部分 -->
            <!-- <div class="relative w-100px h-100px flex-center">
              <el-avatar :src="userProfile.avatar" :size="100" />
              <el-button
                type="info"
                class="absolute bottom-0 right-0 cursor-pointer"
                circle
                :icon="Camera"
                size="small"
                @click="triggerFileUpload"
              />
              <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
            </div>
            <div class="mt-5">
              {{ userProfile.nickname }}
              <el-icon
                class="align-middle cursor-pointer"
                @click="handleOpenDialog(DialogType.ACCOUNT)"
              >
                <Edit />
              </el-icon>
            </div> -->
            <!-- 用户信息描述 -->
            <el-descriptions class="mt-10" border label-width="120px">
              <el-descriptions-item :rowspan="2" :width="140" label="头像" align="center">
                <el-image :src="userProfile.avatar" class="w-20 h-20" />
              </el-descriptions-item>
              <el-descriptions-item label="姓名">
                {{ userProfile.nickname }}
                <!-- <el-icon
                  class="align-middle cursor-pointer"
                  @click="handleOpenDialog(DialogType.ACCOUNT)"
                >
                  <Edit />
                </el-icon> -->
              </el-descriptions-item>
              <!-- 用户名 -->
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><User /></el-icon>
                  用户名
                </template>
                {{ userProfile.username }}
                <el-icon v-if="userProfile.gender === 1" color="blue" class="align-middle">
                  <Male />
                </el-icon>
                <el-icon v-else-if="userProfile.gender === 2" color="pink" class="align-middle">
                  <Female />
                </el-icon>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Phone /></el-icon>
                  手机号码
                </template>
                {{ userProfile.mobile }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Message /></el-icon>
                  邮箱
                </template>
                {{ userProfile.email }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <SvgIcon icon-class="tree" />
                  部门
                </template>
                {{ userProfile.deptName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <SvgIcon icon-class="role" />
                  角色
                </template>
                {{ userProfile.roleNames }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Timer /></el-icon>
                  创建日期
                </template>
                {{ userProfile.createTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <svg-icon size="18" icon-class="education" class="align-middle" />
                  最高学历
                </template>
                <div class="flex items-center gap-2 min-w-[200px]">
                  <span class="font-mono">{{ formatDegree(userProfile.academicDegreeName) }}</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <svg-icon size="18" icon-class="expertise" class="align-middle" />
                  擅长领域
                </template>
                <el-tag v-for="item in userProfile.expertiseList" class="mr-2">
                  {{ item.expertiseName }}
                </el-tag>
              </el-descriptions-item>

              <!-- 咨询师信息 -->
              <template v-if="userProfile.isConsultant">
                <el-descriptions-item>
                  <template #label>
                    <el-icon class="align-middle"><School /></el-icon>
                    所属学校
                  </template>
                  {{ userProfile.schoolName }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <el-icon class="align-middle"><Document /></el-icon>
                    身份证号
                  </template>
                  <div class="flex items-center gap-2 min-w-[300px]">
                    <span class="font-mono">{{ formatIdCard(userProfile.idCard) }}</span>
                    <el-icon class="cursor-pointer" @click="toggleIdCardVisibility">
                      <View v-if="!showIdCard" />
                      <Hide v-else />
                    </el-icon>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <el-icon class="align-middle"><Check /></el-icon>
                    审核状态
                  </template>
                  <el-tag v-if="userProfile.auditStatus === 0" type="info">待审核</el-tag>
                  <el-tag v-else-if="userProfile.auditStatus === 1" type="success">已通过</el-tag>
                  <el-tag v-else-if="userProfile.auditStatus === 2" type="danger">未通过</el-tag>
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <el-icon class="align-middle"><ChatDotRound /></el-icon>
                    审核意见
                  </template>
                  <div
                    :title="userProfile.opinion"
                    class="max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap"
                  >
                    {{ userProfile.opinion }}
                  </div>
                </el-descriptions-item>

                <el-descriptions-item v-if="userProfile.auditStatus === 2">
                  <template #label>
                    <el-icon class="align-middle"><Timer /></el-icon>
                    审核时间
                  </template>
                  {{ userProfile.auditTime }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>
                    <el-icon class="align-middle"><Picture /></el-icon>
                    证件资料
                  </template>
                  <div class="flex flex-col gap-4">
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-500">点击眼睛图标查看/隐藏证件</span>
                      <el-icon class="cursor-pointer" @click="toggleDocumentsVisibility">
                        <View v-if="!showDocuments" />
                        <Hide v-else />
                      </el-icon>
                    </div>
                    <div class="flex items-center gap-4" @click:prevent="">
                      <div class="flex flex-col">
                        <span class="text-sm text-gray-500 mb-1">身份证正面</span>
                        <el-image
                          v-if="userProfile.idCardFrontUrl"
                          :src="userProfile.idCardFrontUrl"
                          :preview-src-list="showDocuments ? [userProfile.idCardFrontUrl] : []"
                          class="w-40 h-24 object-cover"
                          :class="{ 'blur-sm': !showDocuments }"
                        >
                          <template #placeholder>
                            <div class="w-40 h-24 flex-center bg-gray-100">
                              <el-icon><Picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                      <div class="flex flex-col">
                        <span class="text-sm text-gray-500 mb-1">身份证背面</span>
                        <el-image
                          v-if="userProfile.idCardBackUrl"
                          :src="userProfile.idCardBackUrl"
                          :preview-src-list="showDocuments ? [userProfile.idCardBackUrl] : []"
                          class="w-40 h-24 object-cover"
                          :class="{ 'blur-sm': !showDocuments }"
                        >
                          <template #placeholder>
                            <div class="w-40 h-24 flex-center bg-gray-100">
                              <el-icon><Picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                    </div>
                    <div class="flex flex-col">
                      <span class="text-sm text-gray-500 mb-1">学位证书</span>
                      <el-image
                        v-if="userProfile.degreeUrl"
                        :src="userProfile.degreeUrl"
                        :preview-src-list="showDocuments ? [userProfile.degreeUrl] : []"
                        class="w-40 h-24 object-cover"
                        :class="{ 'blur-sm': !showDocuments }"
                      >
                        <template #placeholder>
                          <div class="w-40 h-24 flex-center bg-gray-100">
                            <el-icon><Picture /></el-icon>
                          </div>
                        </template>
                      </el-image>
                    </div>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item
                  v-if="userProfile.otherUrl && userProfile.otherUrl.length > 0"
                  :rowspan="3"
                >
                  <template #label>
                    <el-icon class="align-middle"><Document /></el-icon>
                    其他资料
                  </template>
                  <el-table :data="userProfile.otherUrl" style="width: 100%">
                    <el-table-column prop="fileName" label="文件名称" />
                    <el-table-column prop="url" label="文件链接">
                      <template #default="scope">
                        <el-button type="primary" link @click="() => openUrl(scope.row.url)">
                          查看
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-descriptions-item>
              </template>
            </el-descriptions>

            <!-- 编辑按钮 -->
            <div class="mt-4 flex justify-end">
              <el-button type="primary" @click="handleOpenDialog(DialogType.ACCOUNT)">
                编辑资料
              </el-button>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      <!-- 用户表单 -->
      <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        size="40%"
        :close-on-click-modal="false"
        @close="handleCloseDialog"
      >
        <el-form
          v-if="dialog.type === DialogType.ACCOUNT"
          ref="userFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="" prop="avatar">
            <ImageUpload v-model="formData.avatar" :limit="1" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="formData.username"
              :disabled="!!formData.id"
              placeholder="请输入用户名"
            />
          </el-form-item>

          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="formData.idCard"
              :disabled="!!formData.id"
              placeholder="请输入身份证号"
            />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <Dict v-model="formData.gender" code="gender" />
          </el-form-item>
          <el-form-item label="毕业院校" prop="schoolId">
            <el-select
              v-model="formData.schoolId"
              filterable
              remote
              placeholder="请输入院校名称搜索"
              :remote-method="getSchoolList"
              :loading="schoolLoading"
              @change="handleSchoolChange"
            >
              <el-option
                v-for="item in schoolOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学历" prop="academicDegreeCode">
            <Dict v-model="formData.academicDegreeCode" code="academic_degree" />
          </el-form-item>
          <el-form-item label="擅长领域" prop="expertiseList">
            <Dict v-model="formData.expertiseList" type="select-multiple" code="expertise_field" />
          </el-form-item>

          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
          <el-form-item label="身份证正面照片" prop="idCardFrontUrl">
            <ImageUpload v-model="formData.idCardFrontUrl" :limit="1" is-water-mark />
          </el-form-item>
          <el-form-item label="身份证背面照片" prop="idCardBackUrl">
            <ImageUpload v-model="formData.idCardBackUrl" :limit="1" is-water-mark />
          </el-form-item>
          <el-form-item label="学位证书照片" prop="degreeUrl">
            <ImageUpload v-model="formData.degreeUrl" :limit="1" is-water-mark />
          </el-form-item>
          <el-form-item label="其他资料" prop="otherUrl">
            <FileUpload v-model="formData.otherUrl" />
          </el-form-item>
        </el-form>
        <!-- 修改密码 -->
        <el-form
          v-if="dialog.type === DialogType.PASSWORD"
          ref="passwordChangeFormRef"
          :model="passwordChangeForm"
          :rules="passwordChangeRules"
          :label-width="100"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="passwordChangeForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordChangeForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordChangeForm.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <el-form
          v-else-if="dialog.type === DialogType.MOBILE"
          ref="mobileBindingFormRef"
          :model="mobileBindingForm"
          :rules="mobileBindingRules"
          :label-width="100"
        >
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="mobileBindingForm.mobile" style="width: 250px" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="mobileBindingForm.code" style="width: 250px">
              <template #append>
                <el-button
                  class="ml-5"
                  :loading="codeLoading"
                  :disabled="mobileCountdown > 0"
                  @click="handleSendVerificationCode('MOBILE')"
                >
                  {{ mobileCountdown > 0 ? `${mobileCountdown}s后重新发送` : "发送验证码" }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <!-- 绑定邮箱 -->
        <el-form
          v-else-if="dialog.type === DialogType.EMAIL"
          ref="emailBindingFormRef"
          :model="emailBindingForm"
          :rules="emailBindingRules"
          :label-width="100"
        >
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="emailBindingForm.email" style="width: 250px" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="emailBindingForm.code" style="width: 250px">
              <template #append>
                <el-button
                  class="ml-5"
                  :disabled="emailCountdown > 0"
                  :loading="codeLoading"
                  @click="handleSendVerificationCode('EMAIL')"
                >
                  {{ emailCountdown > 0 ? `${emailCountdown}s后重新发送` : "发送验证码" }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-drawer>
      <!-- 安全设置  -->
      <el-tab-pane label="安全设置">
        <el-card>
          <!-- 账户密码 -->
          <el-row>
            <el-col :span="16">
              <div class="font-bold">账户密码</div>
              <div class="text-14px mt-2">
                定期修改密码有助于保护账户安全
                <el-button
                  type="primary"
                  plain
                  size="small"
                  class="ml-5"
                  @click="() => handleOpenDialog(DialogType.PASSWORD)"
                >
                  修改
                </el-button>
              </div>
            </el-col>
          </el-row>
          <!-- 绑定手机 -->
          <!-- <div class="mt-5">
            <div class="font-bold">绑定手机</div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.mobile">已绑定手机号：{{ userProfile.mobile }}</span>
              <span v-else>未绑定手机</span>
              <el-button
                v-if="userProfile.mobile"
                type="primary"
                plain
                size="small"
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)"
              >
                更换
              </el-button>
              <el-button
                v-else
                type="primary"
                plain
                size="small"
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)"
              >
                绑定
              </el-button>
            </div>
          </div> -->
          <!-- 绑定邮箱 -->
          <div class="mt-5">
            <div class="font-bold">绑定邮箱</div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.email">已绑定邮箱：{{ userProfile.email }}</span>
              <span v-else>未绑定邮箱</span>
              <el-button
                v-if="userProfile.email"
                type="primary"
                plain
                size="small"
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)"
              >
                更换
              </el-button>
              <el-button
                v-else
                type="primary"
                plain
                size="small"
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)"
              >
                绑定
              </el-button>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import UserAPI, {
  UserProfileVO,
  UserProfileForm,
  UserForm,
  PasswordChangeForm,
  MobileBindingForm,
  EmailBindingForm,
} from "@/api/system/user";

import {
  User,
  Phone,
  Message,
  Male,
  Female,
  Timer,
  School,
  Document,
  Check,
  ChatDotRound,
  Picture,
  View,
  Hide,
} from "@element-plus/icons-vue";
import DeptAPI from "@/api/system/dept";
import { getAllSchools, SchoolOption } from "@/api/school";
import { EMAIL_PATTERN, MOBILE_PATTERN } from "@/constants/rules";
import { FormRules } from "element-plus";
import { profile } from "console";
import { useDictStore, useUserStore } from "@/store";

const userProfile = ref<UserProfileVO>({});

enum DialogType {
  ACCOUNT = "account",
  PASSWORD = "password",
  MOBILE = "mobile",
  EMAIL = "email",
}
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
const dialog = reactive({
  visible: false,
  title: "",
  type: "" as DialogType,
});
const formData = reactive<UserForm>({
  status: 1,
});
const rules = reactive<FormRules>({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  idCard: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|10|11|12)(0[1-9]|[1-2][0-9]|30|31)\d{3}[0-9Xx]$/,
      message: "请输入正确的身份证号",
      trigger: "change",
    },
  ],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  academicDegreeCode: [{ required: true, message: "请选择学历", trigger: "change" }],
  expertiseList: [{ required: true, message: "请选择擅长领域", trigger: "change" }],
  schoolId: [{ required: true, message: "请选择毕业院校", trigger: "change" }],

  email: [
    {
      required: true,
      message: "邮箱不能为空",
      trigger: "blur",
    },
    {
      pattern: EMAIL_PATTERN,
      message: "请输入正确的邮箱地址",
      trigger: "change",
    },
  ],
  mobile: [
    {
      required: true,
      message: "手机号码不能为空",
      trigger: "blur",
    },
    {
      pattern: MOBILE_PATTERN,
      message: "请输入正确的手机号码",
      trigger: "change",
    },
  ],
  idCardFrontUrl: [{ required: true, message: "身份证正面照片不能为空", trigger: "change" }],
  idCardBackUrl: [{ required: true, message: "身份证背面照片不能为空", trigger: "change" }],
  degreeUrl: [{ required: true, message: "学位证书照片不能为空", trigger: "change" }],
  otherUrl: [{ required: true, message: "其他资料不能为空", trigger: "change" }],
});
// 学校选择变化时设置学校名称
function handleSchoolChange(schoolId: number) {
  const school = schoolOptions.value.find((item) => item.id === schoolId);
  if (school) {
    formData.schoolName = school.name;
  }
}
const mobileCountdown = ref(0);
const emailCountdown = ref(0);
const userProfileForm = reactive<UserProfileForm>({});

const mobileTimer = ref<NodeJS.Timeout | null>(null);

const emailTimer = ref<NodeJS.Timeout | null>(null);

const schoolOptions = ref<SchoolOption[]>([]);
const schoolLoading = ref(false);

// 获取学校列表
async function getSchoolList(query: string) {
  schoolLoading.value = true;
  try {
    schoolOptions.value = await getAllSchools(query);
  } finally {
    schoolLoading.value = false;
  }
}
// 邮箱校验规则
const emailBindingRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: EMAIL_PATTERN,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};
const handleOpenDialog = async (type: DialogType) => {
  dialog.type = type;
  dialog.visible = true;

  switch (type) {
    case DialogType.ACCOUNT:
      deptOptions.value = await DeptAPI.getOptions();
      dialog.title = "账号资料";
      UserAPI.getFormData(userProfile.value.id as number).then((data) => {
        Object.assign(formData, { ...data });
        formData.schoolId = data.schoolId?.toString();
        formData.otherUrl =
          data?.otherUrl?.map?.((item) => ({
            ...item,
            name: item.fileName,
            url: item.url,
          })) || [];
      });
      if (userProfile.value.schoolId) {
        getSchoolList(userProfile.value.schoolName || "");
      }
      break;
    case DialogType.PASSWORD:
      dialog.title = "修改密码";
      break;
    case DialogType.MOBILE:
      dialog.title = "绑定手机";
      break;
    case DialogType.EMAIL:
      dialog.title = "绑定邮箱";
      break;
  }
};

const userStore = useUserStore();
const loadUserProfile = async () => {
  const data = await UserAPI.getProfile();
  userProfile.value = data;
  // 更新 store头像地址
  userStore.userInfo.avatar = data.avatar;
};

onMounted(async () => {
  if (mobileTimer.value) {
    clearInterval(mobileTimer.value);
  }
  if (emailTimer.value) {
    clearInterval(emailTimer.value);
  }
  await loadUserProfile();
});
const userFormRef = ref(ElForm);
const passwordChangeFormRef = ref(ElForm);
const mobileBindingFormRef = ref(ElForm);
const emailBindingFormRef = ref(ElForm);
const mobileBindingForm = reactive<MobileBindingForm>({});
const emailBindingForm = reactive<EmailBindingForm>({});
// 手机号校验规则
const mobileBindingRules = {
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: MOBILE_PATTERN,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  if (dialog.type === DialogType.ACCOUNT) {
    userFormRef.value.resetFields();
  } else if (dialog.type === DialogType.PASSWORD) {
    passwordChangeFormRef.value.resetFields();
  } else if (dialog.type === DialogType.MOBILE) {
    mobileBindingFormRef.value.resetFields();
  } else if (dialog.type === DialogType.EMAIL) {
    emailBindingFormRef.value.resetFields();
  }
  formData.id = undefined;
  formData.status = 1;
  schoolOptions.value = [];
}
const openUrl = (url: string) => {
  window.open(url, "_blank");
};
const academicDegreeList = reactive<Record<string, string>>({});
const expertiseList = reactive<Record<string, { dictCode: string; name: string }>>({});
// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  if (dialog.type === DialogType.ACCOUNT) {
    userFormRef.value.validate((valid: boolean) => {
      if (valid) {
        const userId = formData.id;
        formData.expertiseCodes = formData.expertiseList?.map((item) => {
          return expertiseList[item as string];
        });
        formData.academicDegreeName = academicDegreeList[formData.academicDegreeCode as string];

        // 确保schoolName被正确设置
        if (formData.schoolId && !formData.schoolName) {
          const schoolId =
            typeof formData.schoolId === "string" ? parseInt(formData.schoolId) : formData.schoolId;
          const school = schoolOptions.value.find((item) => item.id === schoolId);
          if (school) {
            formData.schoolName = school.name;
          }
        }

        formData.otherUrl = formData.otherUrl?.map((item) => ({
          name: item.fileName,
          url: item.url,
          fileName: item.name,
        }));
        formData.status = 1;
        if (userId) {
          UserAPI.update(userId, formData).then(() => {
            const passIndex = userStore.userInfo.perms.findIndex(
              (item) => item === "sys:course:pass"
            );
            if (passIndex !== -1) {
              userStore.userInfo.perms.splice(passIndex, 1);
              console.log(userStore.userInfo.perms);
            }
            ElMessage.success("修改成功");
            handleCloseDialog();
            loadUserProfile();
          });
        }
      }
    });
  } else if (dialog.type === DialogType.PASSWORD) {
    passwordChangeFormRef.value.validate((valid: boolean) => {
      if (valid) {
        if (passwordChangeForm.newPassword !== passwordChangeForm.confirmPassword) {
          ElMessage.error("两次输入的密码不一致");
          return;
        }
        UserAPI.changePassword(passwordChangeForm).then(() => {
          ElMessage.success("密码修改成功");
          handleCloseDialog();
        });
      }
    });
  } else if (dialog.type === DialogType.MOBILE) {
    mobileBindingFormRef.value.validate((valid: boolean) => {
      if (valid) {
        UserAPI.bindMobile(mobileBindingForm).then(() => {
          ElMessage.success("手机号绑定成功");
          handleCloseDialog();
          loadUserProfile();
        });
      }
    });
  } else if (dialog.type === DialogType.EMAIL) {
    emailBindingFormRef.value.validate((valid: boolean) => {
      if (valid) {
        UserAPI.bindEmail(emailBindingForm).then(() => {
          ElMessage.success("邮箱绑定成功");
          handleCloseDialog();
          loadUserProfile();
        });
      }
    });
  }
}, 1000);
const dictStore = useDictStore();
onMounted(() => {
  // 处理擅长领域集合
  dictStore.getDictionary("expertise_field").reduce((pre, cur) => {
    pre[cur.value] = { dictCode: cur.value, name: cur.label };
    return pre;
  }, expertiseList);
  // 处理学历集合
  dictStore.getDictionary("academic_degree").reduce((pre, cur) => {
    pre[cur.value] = cur.label;
    return pre;
  }, academicDegreeList);

  // 初始加载一些常见学校数据，以便在表格中显示
  getSchoolList("");
});

// 添加证件号码显示状态
const showIdCard = ref(false);
const showDegree = ref(false);
const showDocuments = ref(false);

// 添加证件号码显示/隐藏切换函数
const toggleIdCardVisibility = () => {
  showIdCard.value = !showIdCard.value;
};

const toggleDegreeVisibility = () => {
  showDegree.value = !showDegree.value;
};

const toggleDocumentsVisibility = () => {
  showDocuments.value = !showDocuments.value;
};

// 添加证件号码格式化函数
const formatIdCard = (idCard: string | undefined) => {
  if (!idCard) return "";
  if (showIdCard.value) {
    return idCard;
  }
  return idCard.replace(/^(.{6})(?:\d+)(.{4})$/, "$1********$2");
};

const formatDegree = (degree: string | undefined) => {
  if (!degree) return "";
  if (showDegree.value) {
    return degree;
  }
  return degree.replace(/^(.{2})(?:\d+)(.{2})$/, "$1********$2");
};

const passwordChangeForm = reactive<PasswordChangeForm>({});
// 修改密码校验规则
const passwordChangeRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPassword: [{ required: true, message: "请再次输入新密码", trigger: "blur" }],
};
const codeLoading = ref(false);
/**
 *  发送验证码
 *
 * @param contactType 联系方式类型 MOBILE: 手机号码  EMAIL: 邮箱
 */
// TODO: 发送验证码,未完善后期处理，1. 发送按钮 loading 2. 发送邮箱，邮箱服务器链接失败 3. 手机验证码发送未购买阿里云
const handleSendVerificationCode = async (contactType: string) => {
  codeLoading.value = true;
  if (contactType === "MOBILE") {
    if (!mobileBindingForm.mobile) {
      ElMessage.error("请输入手机号");
      return;
    }
    // 验证手机号格式
    if (!MOBILE_PATTERN.test(mobileBindingForm.mobile)) {
      ElMessage.error("手机号格式不正确");
      return;
    }

    mobileCountdown.value = 60;
    mobileTimer.value = setInterval(() => {
      if (mobileCountdown.value > 0) {
        mobileCountdown.value -= 1;
      } else {
        clearInterval(mobileTimer.value!);
      }
    }, 1000);
  } else if (contactType === "EMAIL") {
    if (!emailBindingForm.email) {
      ElMessage.error("请输入邮箱");
      return;
    }
    // 验证邮箱格式
    if (!EMAIL_PATTERN.test(emailBindingForm.email)) {
      ElMessage.error("邮箱格式不正确");
      return;
    }
    UserAPI.sendVerificationCode(emailBindingForm.email, "EMAIL")
      .then(() => {
        ElMessage.success("验证码发送成功");
        emailCountdown.value = 60;
        emailTimer.value = setInterval(() => {
          if (emailCountdown.value > 0) {
            emailCountdown.value -= 1;
          } else {
            clearInterval(emailTimer.value!);
          }
        }, 1000);
      })
      .finally(() => {
        codeLoading.value = false;
      });
  }
};
</script>

<style lang="scss" scoped>
/** 关闭tag标签  */
.app-container {
  /* 50px = navbar = 50px */
  height: calc(100vh - 50px);
  background: var(--el-fill-color-blank);

  :deep(.el-descriptions) {
    .el-descriptions__label {
      min-width: 120px;
      width: 120px;
      white-space: nowrap;
    }

    .el-descriptions__content {
      min-width: 200px;
    }

    .el-descriptions__cell {
      padding: 12px 16px;
    }
  }
}

/** 开启tag标签  */
.hasTagsView {
  .app-container {
    /* 84px = navbar + tags-view = 50px + 34px */
    height: calc(100vh - 84px);
  }
}
</style>
